package zack.gateway.core.bind;

import zack.gateway.core.mapping.HttpStatement;
import zack.gateway.core.session.GatewaySession;
import net.sf.cglib.core.Signature;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.InterfaceMaker;
import org.objectweb.asm.Type;

import java.util.HashMap;
import java.util.Map;

/**映射代理工厂，为session和http调用创建代理对象
 * @author A1793
 */
public class MapperProxyFactory {

    private String uri;

    private final Map<String,IGenericReference> mapperProxyMap = new HashMap();

    public MapperProxyFactory(String uri) {
        this.uri = uri;
    }

    public IGenericReference newInstance(GatewaySession session) {
        MapperProxy mapperProxy = new MapperProxy(uri, session);
        HttpStatement httpStatement = session.getConfiguration().getHttpStatement(uri);
        InterfaceMaker interfaceMaker = new InterfaceMaker();
        interfaceMaker.add(new Signature(httpStatement.getMethodName(), Type.getType(String.class),new Type[]{Type.getType(String.class)}),null);
        Class<?> interfaceClass = interfaceMaker.create();
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(Object.class);
        enhancer.setInterfaces(new Class[]{interfaceClass, IGenericReference.class});
        enhancer.setCallback(mapperProxy);
        return (IGenericReference) enhancer.create();

    }
}
